package com.micdp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Hdfd client pool
 * Created by hadoop on 2017/8/25/025.
 */
public class HdfsPool {

    private static final HdfsPool instance = new HdfsPool();
    private BlockingQueue<HdfsClient> hdfsClients = null;
    private static String fsDefaultFS = "";

    static {
        Properties props = new Properties();
        InputStream in = HdfsPool.class.getClassLoader().getResourceAsStream("hdfs.properties");
        try {
            props.load(in);
            fsDefaultFS = props.getProperty("fs.default.fs");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HdfsPool() {
        this(8);
    }
    private HdfsPool(int nHdfsClient) {
        hdfsClients = new ArrayBlockingQueue<>(nHdfsClient);
        for (int i=0; i<nHdfsClient; i++) {
            put(new HdfsClient(fsDefaultFS));
        }
    }

    public static HdfsPool getInstance() {
        return instance;
    }

    public HdfsClient take() {
        try {
            return hdfsClients.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void put(HdfsClient hdfsClient) {
        if (null == hdfsClient) {
            return ;
        }
        try {
            hdfsClients.put(hdfsClient);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
